package cn.edu.tju.scs.network.ftp.client;

import cn.edu.tju.scs.network.ftp.utils.CmdEnum;
import cn.edu.tju.scs.network.ftp.utils.CommandLine;

import java.io.*;
import java.net.Socket;

/**
 * Created by catold on 16/1/7.
 */
public class TransferfileClient {
    Socket ClientSoc;

    DataInputStream din;
    DataOutputStream dout;
    BufferedReader br;

    TransferfileClient(Socket soc) {
        try {
            ClientSoc = soc;
            din = new DataInputStream(ClientSoc.getInputStream());
            dout = new DataOutputStream(ClientSoc.getOutputStream());
            br = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception ex) {
        }
    }

    void SendFile(CommandLine commandLine) throws Exception {
        if (commandLine.args == null || commandLine.args.length == 0) {
            System.out.println("参数错误");
            return;
        }
        String filename = commandLine.args[0];
        File f = new File(filename);
        if (!f.exists()) {
            dout.writeUTF("File not exists");
            System.out.println("文件不存在");
            return;
        } else {
            dout.writeUTF("File exists");
        }

        String msgFromServer = din.readUTF();
        if (msgFromServer.compareTo("File Already Exists") == 0) {
            String Option;
            System.out.println("文件已经存在. 是否覆盖(Y/N) ?");
            Option = br.readLine();
            if (Option.equals("Y")) {
                dout.writeUTF("Y");
            } else {
                dout.writeUTF("N");
                return;
            }
        }

        System.out.println("发送文件中...");
        FileInputStream fin = new FileInputStream(f);
        int ch;
        do {
            ch = fin.read();
            dout.writeUTF(String.valueOf(ch));
        } while (ch != -1);
        fin.close();
        System.out.println("文件发送完成");
    }

    void CDInstruction(String path) throws Exception {
        String msgFromServer = din.readUTF();
        if (msgFromServer.compareTo("Directory found") == 0) {
            String dir = din.readUTF();
            System.out.println("已进入路径 " + dir);
        } else {
            System.out.println("未找到路径 " + path);
        }
    }

    void LSInstruction() throws Exception {
        String msgFromServer = din.readUTF();
        System.out.println(msgFromServer);
    }

    void MKDIRInstruction() throws Exception {
        String msgFromServer = din.readUTF();
        if (msgFromServer.compareTo("Mkdir success") == 0) {
            System.out.println("文件夹创建成功");
        } else {
            System.out.println("创建失败，文件夹已存在");
        }
    }

    void PWDInstruction() throws Exception {
        String msgFromServer = din.readUTF();
        System.out.println("当前路径为：" + msgFromServer);
    }

    void RMDIRInstruction() throws Exception {
        String msgFromServer = din.readUTF();
        if (msgFromServer.compareTo("Rmdir success") == 0) {
            System.out.println("文件夹删除成功");
        } else {
            System.out.println("文件夹删除失败");
        }
    }

    void DELETEInstruction() throws Exception {
        String msgFromServer = din.readUTF();
        if (msgFromServer.compareTo("delete success") == 0) {
            System.out.println("文件删除成功");
        } else {
            System.out.println("文件删除失败");
        }
    }


    void ReceiveFile(CommandLine commandLine) throws Exception {
        String msgFromServer = din.readUTF();

        if (msgFromServer.compareTo("File Not Found") == 0) {
            System.out.println("服务器上该文件不存在");
            return;
        } else if (msgFromServer.compareTo("READY") == 0) {
            System.out.println("接受文件中...");
            if (commandLine.args == null || commandLine.args.length == 0) {
                System.out.println("参数错误");
                return;
            }
            String filename = commandLine.args[0];

            File f = new File(filename);

            if (f.exists()) {
                String Option;
                System.out.println("文件已经存在. 是否覆盖(Y/N) ?");
                Option = br.readLine();
                dout.writeUTF("File already exists");

                dout.writeUTF(Option);
                if (Option.equals("N")) {
                    dout.flush();
                    return;
                }
            } else {
                dout.writeUTF("File not exists");

            }
            FileOutputStream fout = new FileOutputStream(f);
            int ch;
            String temp;
            do {
                temp = din.readUTF();
                ch = Integer.parseInt(temp);
                if (ch != -1) {
                    fout.write(ch);
                }
            } while (ch != -1);
            fout.close();
            System.out.print("接收文件成功:");
            System.out.println("路径为" + f.getAbsolutePath());
        }


    }

    public void displayMenu() throws Exception {
        while (true) {
            CommandLine commandLine = CommandLine.buildFromLine(br.readLine());

            dout.writeUTF(commandLine.source);

            if (commandLine.isCmd(CmdEnum.CD)) {
                //将路径传给后台,并处理返回 eg: Request:cd user  Response: 路径不存在 | 进入路径
                if(commandLine.args == null){
                    System.out.println("参数错误");
                    continue;
                }
                CDInstruction(commandLine.args[0]);
            } else if (commandLine.isCmd(CmdEnum.DELETE)) {
                // 将路径传给后台,并处理返回 eg: Request:delete file.txt  Response: file.txt doesn't exist | OK
                if(commandLine.args == null){
                    System.out.println("参数错误");
                    continue;
                }
                DELETEInstruction();
            } else if (commandLine.isCmd(CmdEnum.LS)) {
                //eg: Request:ls  Response: user test (各种文件名)
                LSInstruction();
            } else if (commandLine.isCmd(CmdEnum.MKDIR)) {
                //eg: Request:mkdir test  Response: test already exist | OK
                if(commandLine.args == null){
                    System.out.println("参数错误");
                    continue;
                }
                MKDIRInstruction();
            } else if (commandLine.isCmd(CmdEnum.PWD)) {
                //显示user当前目录 eg: Request:pwd  Response: /User/local/test
                PWDInstruction();
            } else if (commandLine.isCmd(CmdEnum.RMDIR)) {
                // Request:rmdir test  Response: test doesn't exist | OK
                if(commandLine.args == null){
                    System.out.println("参数错误");
                    continue;
                }
                RMDIRInstruction();
            } else if (commandLine.isCmd(CmdEnum.SEND)) {
                SendFile(commandLine);
            } else if (commandLine.isCmd(CmdEnum.GET)) {
                ReceiveFile(commandLine);
            } else if (commandLine.isCmd(CmdEnum.BYE)) {
                System.exit(1);
            } else {
                System.out.println("命令不存在");
            }
        }
    }
}